package com.ecommerce.repository;

import com.ecommerce.entity.Review;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface ReviewRepository extends JpaRepository<Review, Long> {
    
    // 根据商品ID查找评价
    Page<Review> findByProductIdOrderByCreatedAtDesc(Long productId, Pageable pageable);
    
    // 根据商品ID查找所有评价
    List<Review> findByProductIdOrderByCreatedAtDesc(Long productId);
    
    // 根据用户ID查找评价
    Page<Review> findByUserIdOrderByCreatedAtDesc(Long userId, Pageable pageable);
    
    // 根据商品ID和用户ID查找评价（检查用户是否已评价该商品）
    Optional<Review> findByProductIdAndUserId(Long productId, Long userId);
    
    // 根据商品ID统计评价数量
    long countByProductId(Long productId);
    
    // 根据商品ID计算平均评分
    @Query("SELECT AVG(r.rating) FROM Review r WHERE r.product.id = :productId")
    Double getAverageRatingByProductId(@Param("productId") Long productId);
    
    // 根据商品ID统计各评分数量
    @Query("SELECT r.rating, COUNT(r) FROM Review r WHERE r.product.id = :productId GROUP BY r.rating ORDER BY r.rating DESC")
    List<Object[]> getRatingDistributionByProductId(@Param("productId") Long productId);
    
    // 根据商品ID查找评分大于等于指定值的评价
    Page<Review> findByProductIdAndRatingGreaterThanEqualOrderByCreatedAtDesc(Long productId, Integer rating, Pageable pageable);
    
    // 根据商品ID查找评分小于指定值的评价
    Page<Review> findByProductIdAndRatingLessThanOrderByCreatedAtDesc(Long productId, Integer rating, Pageable pageable);
} 